import { defineComponent, h, Ref, ref, toRefs, PropType, watch, onMounted, onUnmounted } from "vue";
import Highcharts, { Chart, Options } from 'highcharts'

const vueHighcharts = defineComponent({
    name: 'vueHighcharts',
    props: {
        type: {
            type: String as PropType<keyof typeof Highcharts>,
            default: 'chart'
        },
        // 让传入的options必须是highcharts的options
        options: {
            type: Object as PropType<Options>,
            required: true,  // 必须传入
        },
        // 更新时是否重新绘制
        redrawOnUpdate: {   
            type: Boolean,
            default: true
        },
        // 每一次独立更新
        oneToOneUpdate: {
            type: Boolean,
            default: true
        }
    },
    setup(props, {emit}) {
        //  html引用
        const chartRef = ref(null);
        const chart:Ref<Chart | null> = ref(null);  // 最后要去渲染的实际的值
        const { options } = toRefs(props);
        if (options?.value) {
            watch(options, (newvalue)=>{
                if (chart.value === null) {
                    // chart.value.update
                    (<Ref<Chart>>(chart as unknown)).value.update(
                        newvalue,
                        props.redrawOnUpdate,
                    )
                }
            }, {
                deep: true
            })
            onMounted(()=>{
                // Highcharts.chart('container', options, ()=>{});
                chart.value = Highcharts[props.type](chartRef.value, options.value, ()=>{
                    emit('onRender');
                })
            })

            // 卸载
            onUnmounted(()=>{
                if (chart.value) {
                    // 销毁图表
                    (<Ref<Chart>>(chart as unknown)).value.destroy();
                    emit('destory成功');
                }
            })
        } else {
            console.error('请传递渲染函数组件必须的参数')
        } 

        return {
            chartRef,
            chart
        }
    },
    render() {
        return h('div', {
            class: 'vue-highcharts',
            ref: 'chartRef',
        });
    }
})

export default vueHighcharts;